import router from '@/router'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import useUserStore from '@/store/modules/user'
import setting from '@/setting'

nprogress.configure({ showSpinner: false })

// 前置守卫
router.beforeEach(async (to: any, from: any, next: any) => {
  let userStore = useUserStore()
  let { token, username } = userStore

  document.title = setting.title + '-' + to.meta.title

  // 进度条
  nprogress.start()
  // 路由鉴权
  if (token) {
    if (to.path == '/login') {
      next({ path: '/home' })
    } else {
      if (username) {
        next()
      } else {
        try {
          await userStore.getUserInfo()
          next()
        } catch (error) {
          // token过期
          await userStore.userLogout()
          next({ path: '/login', query: { redirect: to.path } })
        }
      }
    }
  } else {
    if (to.path == '/login') {
      next()
    } else {
      next({ path: '/login', query: { redirect: to.path } })
    }
  }
})

// 后置守卫
router.afterEach((to: any, from: any) => {
  nprogress.done()
})
